﻿using System.Linq;
using System;
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

namespace ZyGame.Transport
{
    public class UploadFileList
    {
        private float uploadCount = 0;
        private int completionCount = 0;
        public List<UploadHandle> worker = new List<UploadHandle>();
        public Queue<UploadHandle> waiting = new Queue<UploadHandle>();

        public event Action completionEvent;
        public event Action<float> progressEvent;

        public void Upload(UploadConfig config, string files)
        {
            if (files is null || files.Length is 0)
            {
                return;
            }
            uploadCount = files.Length;
            waiting.Enqueue(new UploadHandle(files, config));
        }

        public void OnStart()
        {
            Client.Tools.StartCoroutine(OnStartup());
        }

        private IEnumerator OnStartup()
        {
            yield return new WaitUntil(CheckCompletion);
            if (completionEvent is not null)
            {
                completionEvent?.Invoke();
                completionEvent = null;
            }
        }

        private IEnumerator UploadHandler(UploadHandle upload)
        {
            yield return upload.OnStart();
            if (upload.state is UploadState.Failurefuly)
            {
                if (upload.TryUpload())
                {
                    Client.Console.WriteLine("重试：" + upload.filePath);
                    waiting.Enqueue(upload);
                }
                else
                {
                    Debug.LogError("资源上传错误:" + upload.filePath);
                }
            }
            else
            {
                completionCount++;
            }
            worker.Remove(upload);
        }

        private bool CheckCompletion()
        {
            bool state = waiting.Count is 0 && worker.Count is 0;
            if (state is false)
            {
                if (waiting.Count is not 0)
                {
                    if (waiting.TryDequeue(out UploadHandle upload))
                    {
                        worker.Add(upload);
                        Client.Tools.StartCoroutine(UploadHandler(upload));
                    }
                }
                float p = (worker.Sum(x => x.progres) + completionCount) / uploadCount;
                progressEvent?.Invoke(p);
            }
            return state;
        }
    }
   
}